import { Button, message } from "tea-component";
import React from "react";
import { useDialogRef } from "../../../../utils/react-use/useDialog";
import { CreateGroupDialog } from "./CreateGroupDialog";
import "./title.scss";
import { GroupList } from "../../../../api";
import { useSelector } from "react-redux";
import Toast from "../../../../components/toast/Toast";
import { sleep } from "../../../../utils/tools";
import { SearchGroupDialog } from "./SearchGroupDialog";


export const Title = (props: { onRefresh: () => Promise<GroupList>; groupNum:number}): JSX.Element => {
  const { onRefresh,groupNum} = props;
  const { userId } = useSelector((state: State.RootState) => state.userInfo);

  const createGroupDialogRef = useDialogRef();
  const searchGroupDialogRef = useDialogRef();
  return (
    <>
      <div className="title">
        <div className="title--left">
          <span className="title--left__icon" />
          <span className="title--left__text">我的群组</span>
        </div>
        <div>
          <Button  className="title--right__button" type="primary"  onClick={() =>{
              if(Toast.serConfig && groupNum >= Number(Toast.serConfig.maximum_of_creations) ){
                message.error({ style:{top:"50%"},content: `群数量已经达到上限`});
                return;
              }
              createGroupDialogRef.current.open({ userId });
            }} >
            创建群聊
          </Button>
          <Button  className="title--right__button" type="primary"  style={{marginLeft:"10px"}} onClick={() =>{
              searchGroupDialogRef.current.open({ userId });
            }} >
            搜索群
          </Button>
        </div>
      </div>
      <CreateGroupDialog dialogRef={createGroupDialogRef} onSuccess={async () => {
          await sleep(1000);
          await onRefresh();
        }}/>
      <SearchGroupDialog dialogRef={searchGroupDialogRef} onSuccess={async () => {
          await sleep(1000);
          await onRefresh();
        }}/>
    </>
  );
};
